package com.uniledger.exchange.home.scheme.fragment.topup;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.orhanobut.logger.Logger;
import com.uniledger.commonlib.easymoney.EasyMoneyEditText;
import com.uniledger.commonlib.easymoney.IconMoneyEditText;
import com.uniledger.commonlib.pinkeyboard.IKeyboardListener;
import com.uniledger.commonlib.pinkeyboard.KeyboardDialog;
import com.uniledger.exchange.R;
import com.uniledger.exchange.bank.AddBankActivity;
import com.uniledger.exchange.bank.BankCard;
import com.uniledger.exchange.bank.BottomBankAdapter;
import com.uniledger.exchange.bank.BottomSelectDialog;
import com.uniledger.exchange.bank.Gateway;
import com.uniledger.exchange.bank.GatewayAdapter;
import com.uniledger.exchange.model.HttpResult;
import com.uniledger.exchange.model.OkSingleton;
import com.uniledger.exchange.model.StellarList;
import com.uniledger.exchange.model.api.Api;
import com.uniledger.exchange.model.rx.RxException;
import com.uniledger.exchange.model.rx.RxProgress;
import com.uniledger.exchange.model.rx.RxSchedulers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

import static com.uniledger.commonlib.bigdecimalutils.BigDecimalUtils.is;


/**
 *
 */
public class IntoFragment extends TopUpFragment implements BottomSelectDialog.OnSelectBankListener, IKeyboardListener {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;

    @BindView(R.id.edit_amount)
    IconMoneyEditText iconMoneyEditText;

    EasyMoneyEditText editAmount;

    @BindView(R.id.select_bank)
    LinearLayout select_bank;

    @BindView(R.id.edit_remark)
    EditText edit_remark;

    @BindView(R.id.bank_name)
    TextView bank_name;

    @BindView(R.id.bank_number)
    TextView bank_number;

    BottomSelectDialog bankDialog;

    BottomBankAdapter bankAdapter;

    BankCard bankCard;

    KeyboardDialog pinDialog;

    public IntoFragment() {
        // Required empty public constructor
    }

    public static IntoFragment newInstance(String param1, String param2) {
        IntoFragment fragment = new IntoFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @OnClick(R.id.select_bank)
    void selectBank() {
        if (bankAdapter != null) {
            bankDialog.show(bankAdapter);
        }
    }

    @OnClick(R.id.edit_remark)
    void clickRemark() {
        listener.getKeyboard().hideKeyboard();
    }


    void selectGateway() {
        bankDialog.show(new GatewayAdapter(getActivity()));
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public void onClick(View v) {
        if (bankCard == null) {
            return;
        }
        String amount = editAmount.getValueString();
        if (is(amount).isPositive()){
            showPayKeyBoard();
        }
    }

    @Override
    public int getViewResourceId() {
        return R.layout.fragment_into;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        editAmount = iconMoneyEditText.getMoneyEditText();
        editAmount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupKeyboard();
            }
        });

        bankDialog = new BottomSelectDialog(getActivity(), getChildFragmentManager());
        bankDialog.init();
        bankDialog.setSelectBankListener(this);

        iconMoneyEditText.setSymbol(R.drawable.ic_common_aed);

        Api.getService().getBankcardList(1, 20)
                .map(new Function<HttpResult<StellarList>, HttpResult<StellarList>>() {
                    @Override
                    public HttpResult<StellarList> apply(HttpResult<StellarList> result) throws Exception {
                        List<BankCard> bankcards = new ArrayList<>();
                        for (BankCard card : result.data.bankcards) {
                            if (TextUtils.equals(OkSingleton.getInstance().getCurrencyCode(), card.cardAssetShort)) {
                                bankcards.add(card);
                            }
                        }
                        result.data.bankcards = bankcards;
                        return result;
                    }
                })
                .compose(RxSchedulers.io_main())
                .compose(RxProgress.applyProgressBar(getActivity()))
                .subscribe(new Consumer<HttpResult<StellarList>>() {
                    @Override
                    public void accept(HttpResult<StellarList> httpResult) throws Exception {

                        if (httpResult.data != null) {
                            bankCard = httpResult.data.bankcards.get(0);
                            bank_name.setText(bankCard.bank);
                            bank_number.setText(bankCard.getCardNumber());
                        }
                        bankAdapter = new BottomBankAdapter(getActivity(), httpResult.data.bankcards);
                    }
                }, new RxException<>(new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                }));

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AddBankActivity.MANGER_CARD_CODE && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                BankCard card = data.getParcelableExtra("BankCard");
                selectBank(card);
                bankDialog.closeDialog();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        bankDialog.closeDialog();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (pinDialog != null) {
            pinDialog.dismiss();
        }
    }

    public void showPayKeyBoard() {
        listener.getKeyboard().hideKeyboard();
        if (pinDialog == null) {
            pinDialog = new KeyboardDialog(getActivity());
            pinDialog.setKeyboardListener(this);
        }
        pinDialog.show();
    }

    /**
     * 选择银行
     *
     * @param card
     */
    @Override
    public void selectBank(BankCard card) {
        bankCard = card;
        bank_name.setText(card.bank);
        bank_number.setText(card.getCardNumber());
    }

    /**
     * 选择网关
     *
     * @param gateway
     */
    @Override
    public void selectGateway(Gateway gateway) {

    }

    void popupKeyboard() {
        listener.getKeyboard().attachTo(editAmount);
    }

    @Override
    public void onPasswordChange(String pwd) {

    }

    @Override
    public void onPasswordComplete(String pwd) {
        String amount = editAmount.getValueString();
        String remark = edit_remark.getText().toString();
        Map<String, String> params = new HashMap<>();
        if (TextUtils.isEmpty(remark)) {
            params.put("remark", "TopUp");
        } else {
            params.put("remark", remark);
        }
        params.put("amount", amount);
        params.put("card_id", bankCard.id + "");
        params.put("stellar_trx_sign", "sign");
        listener.callbackInfo(params);
    }

    @Override
    public void onForgetPwd() {

    }
}
